package com.andnux.android.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.andnux.android.MainApp;
import com.andnux.android.adapter.ChatAdapter;
import com.andnux.android.data.ChatMessage;
import com.andnux.android.data.ChatSession;
import com.andnux.android.data.PageData;
import com.andnux.android.data.SystemUsers;
import com.andnux.android.databinding.ActivityChatBinding;
import com.andnux.android.network.DesignCloudApi;
import com.andnux.android.network.GsonUtils;
import com.andnux.android.network.NotNullConsumer;
import com.andnux.android.network.Result;
import com.andnux.android.network.RetrofitClient;
import com.andnux.android.network.SuccessConsumer;
import com.andnux.android.utils.ImageLoader;
import com.andnux.android.utils.StringUtils;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ChatActivity extends BaseActivity<ActivityChatBinding> {

    private int current = 0;
    private static final int size = 10;
    private ChatSession session;
    private ChatAdapter adapter;
    private final List<ChatMessage> list = new ArrayList<>();
    private DesignCloudApi api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        session = (ChatSession) getIntent().getSerializableExtra("session");
        api = RetrofitClient.getInstance().getServerApi();
        String json = session.getWorks().getFiles();
        List<String> files = GsonUtils.gson.fromJson(json, new TypeToken<List<String>>() {
        }.getType());
        SystemUsers users = MainApp.getApp().getSystemUsers();
        ImageLoader.load(files.get(0), binding.worksImage);
        if (StringUtils.toString(users.getId()).contentEquals(session.getToId())) {
            binding.title.setText(session.getFromUser().getNickname());
            adapter = new ChatAdapter(session.getFromUser());
        } else {
            binding.title.setText(session.getToUser().getNickname());
            adapter = new ChatAdapter(session.getToUser());
        }
        binding.content.setAdapter(adapter);
        binding.worksTitle.setText(session.getWorks().getTitle());
        binding.worksPrice.setText(StringUtils.toString(session.getWorks().getPrice()));

        binding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        binding.buy.setVisibility("1".contentEquals(users.getRole()) ? View.VISIBLE : View.GONE);
        binding.buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChatActivity.this, BuyActivity.class);
                session.getWorks().setUsers(session.getToUser());
                intent.putExtra("works", session.getWorks());
                startActivity(intent);
            }
        });
        binding.smart.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                current++;
                loadData();
            }
        });

        binding.send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = binding.text.getText().toString();
                if (!TextUtils.isEmpty(s)) {
                    sendMessage(s);
                }
            }
        });
        loadData();
    }

    private void sendMessage(String s) {
        SystemUsers users = MainApp.getApp().getSystemUsers();
        ChatMessage vo = new ChatMessage();
        vo.setChatSessionId(session.getSessionId());
        vo.setCreateTime(new Date());
        vo.setDeleted("0");
        vo.setExtjson("");
        vo.setFromId(String.valueOf(users.getId()));
        if (StringUtils.toString(users.getId()).contentEquals(session.getToId())) {
            vo.setToId(session.getFromId());
        } else {
            vo.setToId(session.getToId());
        }
        vo.setUserId(String.valueOf(users.getId()));
        vo.setWorksId(session.getWorksId());
        vo.setMessage(s);
        list.add(vo);
        adapter.setNewData(list);
        binding.text.setText("");
        binding.content.scrollToPosition(adapter.getItemCount() - 1);
        addDisposable(api.chatMessageInsert(vo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SuccessConsumer<Result<Integer>>() {
                    @Override
                    public void onSuccess(Result<Integer> result) {
                        Toast.makeText(ChatActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (throwable != null) {
                            Toast.makeText(ChatActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));

    }

    private void chatMessageRead(List<String> list) {
        addDisposable(api.chatMessageRead(list)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NotNullConsumer<Result<Integer>>() {
                    @Override
                    public void onSuccess(Result<Integer> result) {

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                        if (throwable != null) {
                            Toast.makeText(ChatActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));

    }

    @Override
    public void onMessage(String text) {
        super.onMessage(text);
        current = 0;
        loadData();
    }

    private void loadData() {
        SystemUsers users = MainApp.getApp().getSystemUsers();
        addDisposable(api.chatMessagePage(current, size,
                String.valueOf(users.getId()), session.getWorksId(),
                session.getSessionId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new NotNullConsumer<Result<PageData<List<ChatMessage>>>>() {
                    @Override
                    public void onSuccess(Result<PageData<List<ChatMessage>>> result) {
                        if (current <= 1) {
                            list.clear();
                        }
                        List<ChatMessage> chatMessages = result.getData().getList();
                        List<String> idList = new ArrayList<>();
                        for (ChatMessage message : chatMessages) {
                            idList.add(String.valueOf(message.getId()));
                        }
                        chatMessageRead(idList);
                        list.addAll(0, chatMessages);
                        adapter.setNewData(list);
                        if (chatMessages.size() < size) {
                            binding.smart.finishLoadMoreWithNoMoreData();
                        } else {
                            binding.smart.finishLoadMore();
                        }
                        binding.smart.finishRefresh();
                        binding.content.scrollToPosition(adapter.getItemCount());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        binding.smart.finishLoadMoreWithNoMoreData();
                        binding.smart.finishRefresh();
                        if (throwable != null) {
                            Toast.makeText(ChatActivity.this, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }));

    }
}